// pages/order/add/index.js
import api from "../../../api/index";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    formData: {},

    showShop: false,
    showCoach: false,
    showCourse: false,
    showCard: false,

    coachObj: {
      list: [],
      name: "coach_id",
    },

    courseList: [],
    pValue: 0,

    cardLists: {},
    cardList: [],
    cardVal: 0,
    cardForm: "",

    isAdd: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    this.getCoachList();
    // this.getCoachOrderCourseList();
    Promise.all([this.getCardList("normal"), this.getCardList("single")]).then(
      (res) => {
        let cardLists = {};
        res.forEach((i) => {
          cardLists[i.form] = i.list;
        });
        let formData = {
          form: "card",
          card_form: "normal",
        };
        this.setData({
          formData,
          cardList: cardLists["normal"],
          cardLists,
        });
      }
    );
  },
  getCoachList() {
    api.apiStoreCoachList().then((res) => {
      this.setData({
        "coachObj.list": res.data.list,
      });
    });
  },
  getCardList(form) {
    return new Promise((resolve, reject) => {
      api
        .apiStoreOrderCardList({
          form,
        })
        .then((res) => {
          resolve({
            form,
            list: res.data,
          });
        });
    });
  },
  getCourseList() {
    api
      .apiStoreOrderCourseList({
        coach_id: this.data.formData.coach_id,
      })
      .then((res) => {
        this.setData({
          courseList: res.data.list,
        });
      });
  },
  openPicker(e) {
    if (
      e.currentTarget.dataset.type === "course" &&
      !this.data.formData.coach_id
    ) {
      wx.showToast({
        title: "请先选择教练",
        icon: "none",
      });
      return;
    }
    let key = "";
    switch (e.currentTarget.dataset.type) {
      case "coach":
        key = "showCoach";
        break;
      case "shop":
        key = "showShop";
        break;
      case "course":
        key = "showCourse";
        break;
      case "card":
        key = "showCard";
        break;
    }
    this.setData({
      [key]: true,
    });
  },
  onClose(e) {
    this.setData({
      showShop: false,
      showCoach: false,
      showCourse: false,
      showCard: false,
    });
  },
  changeVal(e) {
    this.setData({
      pValue: e.currentTarget.dataset.id || e.detail.value.card_id,
    });
  },
  getValue(e) {
    let { courseList, cardList, pValue, coachObj } = this.data;
    let data = {};
    let name = e.currentTarget.dataset.name || e.detail.type;
    let value =
      ["course_id", "card_id"].indexOf(name) === -1 ? e.detail.value : pValue;
    if (name === "card_id" && !value) {
      value = cardList[0].card_id;
    }
    data[`formData.${name}`] = value;
    if (name === "coach_id") {
      data["formData.coachLabel"] = coachObj.list.find(
        (i) => i.coach_id === value
      ).nickname;
    }
    if (name === "course_id") {
      let item = courseList.find((i) => i.course_id === value);
      data["formData.courseLabel"] = item.title;
      data["formData.unitPrice"] = item.price;
      data["formData.num"] = item.num;
    }
    if (name === "card_id") {
      let item = cardList.find((i) => i.card_id === value);
      data["formData.cardLabel"] = item.title;
      data["formData.price"] = item.price;
      data["formData.days"] = item.days;
    }
    this.setData(data);
    if (name === "coach_id") {
      this.getCourseList();
    }

    this.onClose();
  },

  onRadioChange(e) {
    let name = e.currentTarget.dataset.name;
    if (name === "form") {
      this.setData({
        formData: {},
      });
    }
    let key = `formData.${name}`;
    let data = {
      [key]: e.detail,
    };
    if (e.detail === "card") {
      data["formData.card_form"] = "normal";
    }
    if (e.detail === "card" || name === "card_form") {
      data["cardList"] = this.data.cardLists[data["formData.card_form"]];
    }
    this.setData(data);
  },
  onAdd() {
    let { formData, isAdd } = this.data;
    if (isAdd) return;
    this.setData({ isAdd: true });
    if (
      (formData.form === "card"
        ? !formData.card_id || !formData.give_days
        : !formData.course_id || !formData.num) ||
      !formData.coupon_cost
    ) {
      wx.showToast({
        title: "必填参数不能为空",
        icon: "none",
      });
      this.setData({ isAdd: false });
      return;
    }
    let param = {
      form: formData.form,
      coupon_cost: formData.coupon_cost,
    };
    if (param.form === "card") {
      param.card_form = formData.card_form;
      param.card_id = formData.card_id;
      param.give_days = formData.give_days;
    } else {
      param.course_id = formData.course_id;
      param.num = formData.num;
    }

    // if (formData.petname) param.petname = formData.petname;
    // if (formData.telephone) param.telephone = formData.telephone;
    if (formData.remark) param.remark = formData.remark;
    api
      .apiStoreOrderAdd(param)
      .then((res) => {
        if (res.code === 1) {
          wx.showToast({
            title: "添加成功",
            icon: "none",
          });
          setTimeout((_) => {
            const pages = getCurrentPages();
            const prevPage = pages[pages.length - 2];
            if (prevPage && prevPage.init) {
              prevPage.init(param.form);
            }
            wx.navigateBack();
          }, 2500);
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
        }
      })
      .finally((_) => {
        this.setData({ isAdd: false });
      });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
